<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title th:text="${restaurant.name + ' - 美食社区'}">餐厅详情 - 美食社区</title>
    <!-- Bootstrap CSS -->
    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.3.1/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome -->
    <link href="https://cdn.bootcdn.net/ajax/libs/font-awesome/6.4.2/css/all.min.css" rel="stylesheet">
    <!-- Lightbox -->
    <link href="https://cdn.bootcdn.net/ajax/libs/lightbox2/2.11.3/css/lightbox.min.css" rel="stylesheet">
    <!-- 高德地图 API 配置 -->
    <script>
        window._AMapSecurityConfig = {
            securityJsCode: 'bfe7f3e393e836da32c0866809ede991',
        }
    </script>
    <script type="text/javascript"
        src="https://webapi.amap.com/maps?v=2.0&key=ab9d237bbfad18a480eae5c6ebec430c"></script>
    <link rel="stylesheet" th:href="@{/css/style.css}">
    <style>
        .restaurant-header {
            position: relative;
            height: 350px;
            background-size: cover;
            background-position: center;
            margin-bottom: 30px;
        }

        .restaurant-header-overlay {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: linear-gradient(to bottom, rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.7));
            display: flex;
            flex-direction: column;
            justify-content: flex-end;
            padding: 30px;
            color: white;
        }

        .restaurant-info {
            background-color: white;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            padding: 20px;
            margin-bottom: 30px;
        }

        .rating-stars {
            color: #ffc107;
            font-size: 24px;
        }

        .price-level {
            color: #28a745;
            font-size: 18px;
        }

        .review-card {
            background-color: white;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            padding: 20px;
            margin-bottom: 20px;
        }

        .review-header {
            display: flex;
            align-items: center;
            margin-bottom: 15px;
        }

        .review-avatar {
            width: 50px;
            height: 50px;
            border-radius: 50%;
            object-fit: cover;
            margin-right: 15px;
        }

        .review-rating {
            margin-left: auto;
            color: #ffc107;
        }

        .review-content {
            margin-bottom: 15px;
        }

        .review-images {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
        }

        .review-image {
            width: 100px;
            height: 100px;
            object-fit: cover;
            border-radius: 5px;
            cursor: pointer;
            transition: transform 0.3s ease;
        }

        .review-image:hover {
            transform: scale(1.05);
        }

        .review-form {
            background-color: white;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            padding: 20px;
            margin-bottom: 30px;
        }

        .rating-input {
            display: flex;
            flex-direction: row-reverse;
            justify-content: flex-end;
        }

        .rating-input input {
            display: none;
        }

        .rating-input label {
            cursor: pointer;
            font-size: 24px;
            color: #ddd;
            margin-right: 5px;
        }

        .rating-input label:hover,
        .rating-input label:hover~label,
        .rating-input input:checked~label {
            color: #ffc107;
        }

        .map-container {
            height: 300px;
            border-radius: 10px;
            overflow: hidden;
            margin-bottom: 30px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }

        .image-preview-container {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            margin-top: 10px;
        }

        .image-preview {
            width: 100px;
            height: 100px;
            object-fit: cover;
            border-radius: 5px;
        }

        .remove-image {
            position: absolute;
            top: 5px;
            right: 5px;
            background-color: rgba(0, 0, 0, 0.5);
            color: white;
            width: 20px;
            height: 20px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
        }
    </style>
</head>

<body>
    <!-- 导航栏 -->
    <nav th:replace="~{common/header :: header}"></nav>

    <div class="restaurant-header" th:style="'background-image: url(' + ${restaurant.image} + ')'">
        <div class="restaurant-header-overlay">
            <h1 th:text="${restaurant.name}">餐厅名称</h1>
            <div class="d-flex align-items-center">
                <div class="rating-stars me-3">
                    <span th:text="${restaurant.rating}"></span>
                    <i class="fas fa-star"></i>
                </div>
                <div class="price-level me-3">
                    <span th:text="${'¥' + #strings.repeat('¥', restaurant.priceLevel - 1)}"></span>
                </div>
                <span class="badge bg-light text-dark" th:text="${restaurant.cuisineType}">菜系</span>
            </div>
        </div>
    </div>

    <div class="container">
        <div class="row">
            <div class="col-lg-8">
                <!-- 餐厅信息 -->
                <div class="restaurant-info">
                    <h3>餐厅信息</h3>
                    <hr>
                    <p><i class="fas fa-map-marker-alt me-2 text-primary"></i><span
                            th:text="${restaurant.address}">地址</span></p>
                    <p><i class="fas fa-utensils me-2 text-primary"></i><span
                            th:text="${restaurant.cuisineType}">菜系</span></p>
                    <p><i class="fas fa-info-circle me-2 text-primary"></i><span
                            th:text="${restaurant.description}">描述</span></p>
                </div>

                <!-- 评论表单 -->
                <div class="review-form" th:if="${session.user != null}">
                    <h3>写评论</h3>
                    <hr>
                    <form id="reviewForm" enctype="multipart/form-data">
                        <input type="hidden" name="restaurantId" th:value="${restaurant.id}">
                        <div class="mb-3">
                            <label class="form-label">评分</label>
                            <div class="rating-input">
                                <input type="radio" id="star5" name="rating" value="5">
                                <label for="star5" class="fas fa-star"></label>
                                <input type="radio" id="star4" name="rating" value="4">
                                <label for="star4" class="fas fa-star"></label>
                                <input type="radio" id="star3" name="rating" value="3">
                                <label for="star3" class="fas fa-star"></label>
                                <input type="radio" id="star2" name="rating" value="2">
                                <label for="star2" class="fas fa-star"></label>
                                <input type="radio" id="star1" name="rating" value="1">
                                <label for="star1" class="fas fa-star"></label>
                            </div>
                        </div>
                        <div class="mb-3">
                            <label for="content" class="form-label">评论内容</label>
                            <textarea class="form-control" id="content" name="content" rows="4" required></textarea>
                        </div>
                        <div class="mb-3">
                            <label for="imageFiles" class="form-label">上传图片</label>
                            <input class="form-control" type="file" id="imageFiles" name="imageFiles" multiple
                                accept="image/*">
                            <div class="image-preview-container" id="imagePreviewContainer"></div>
                        </div>
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-paper-plane me-2"></i>提交评论
                        </button>
                    </form>
                </div>

                <!-- 评论列表 -->
                <h3 class="mt-4 mb-3">用户评论 <span class="badge bg-secondary" th:text="${reviews.size()}">0</span></h3>
                <div th:if="${reviews.isEmpty()}" class="alert alert-info">
                    暂无评论，快来成为第一个评论的人吧！
                </div>
                <div class="review-card" th:each="review : ${reviews}">
                    <div class="review-header">
                        <img th:src="${review.userAvatar != null ? review.userAvatar : '/images/default-avatar.jpg'}"
                            class="review-avatar" alt="用户头像">
                        <div>
                            <h5 class="mb-0" th:text="${review.nickname != null ? review.nickname : review.username}">
                                用户名</h5>
                            <small class="text-muted"
                                th:text="${#temporals.format(review.createTime, 'yyyy-MM-dd HH:mm')}">评论时间</small>
                        </div>
                        <div class="review-rating">
                            <span th:text="${review.rating}"></span>
                            <i class="fas fa-star"></i>
                        </div>
                    </div>
                    <div class="review-content">
                        <p th:text="${review.content}">评论内容</p>
                        <div class="review-images" th:if="${review.images != null && review.images != ''}">
                            <a th:each="image : ${#strings.arraySplit(review.images, ',')}" th:href="${image}"
                                data-lightbox="review-images"
                                th:data-title="${review.nickname != null ? review.nickname : review.username} + '的评论图片'">
                                <img th:src="${image}" class="review-image" alt="评论图片">
                            </a>
                        </div>
                    </div>
                </div>

                <!-- 分页 -->
                <nav aria-label="Page navigation" class="mt-4" th:if="${totalPages > 1}">
                    <ul class="pagination justify-content-center">
                        <li class="page-item" th:classappend="${currentPage == 1 ? 'disabled' : ''}">
                            <a class="page-link"
                                th:href="@{'/restaurant/' + ${restaurant.id} + '?page=' + ${currentPage - 1}}"
                                aria-label="Previous">
                                <span aria-hidden="true">&laquo;</span>
                            </a>
                        </li>
                        <li class="page-item" th:each="i : ${#numbers.sequence(1, totalPages)}"
                            th:classappend="${i == currentPage ? 'active' : ''}">
                            <a class="page-link" th:href="@{'/restaurant/' + ${restaurant.id} + '?page=' + ${i}}"
                                th:text="${i}"></a>
                        </li>
                        <li class="page-item" th:classappend="${currentPage == totalPages ? 'disabled' : ''}">
                            <a class="page-link"
                                th:href="@{'/restaurant/' + ${restaurant.id} + '?page=' + ${currentPage + 1}}"
                                aria-label="Next">
                                <span aria-hidden="true">&raquo;</span>
                            </a>
                        </li>
                    </ul>
                </nav>
            </div>

            <div class="col-lg-4">
                <!-- 地图 -->
                <div class="map-container" id="map"></div>

                <!-- 推荐餐厅 -->
                <div class="card mb-4">
                    <div class="card-header">
                        <h5 class="mb-0">相似餐厅推荐</h5>
                    </div>
                    <div class="list-group list-group-flush">
                        <a th:each="rec : ${recommendations}" th:href="@{'/restaurant/' + ${rec.id}}"
                            class="list-group-item list-group-item-action">
                            <div class="d-flex align-items-center">
                                <img th:src="${rec.image}" alt="餐厅图片" class="me-3"
                                    style="width: 60px; height: 60px; object-fit: cover; border-radius: 5px;">
                                <div>
                                    <h6 class="mb-0" th:text="${rec.name}">餐厅名称</h6>
                                    <div class="d-flex align-items-center mt-1">
                                        <small class="text-warning me-2">
                                            <span th:text="${rec.rating}"></span>
                                            <i class="fas fa-star"></i>
                                        </small>
                                        <small class="text-muted" th:text="${rec.cuisineType}">菜系</small>
                                    </div>
                                </div>
                            </div>
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Bootstrap Bundle with Popper -->
    <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.3.1/js/bootstrap.bundle.min.js"></script>
    <!-- jQuery -->
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <!-- Lightbox -->
    <script src="https://cdn.bootcdn.net/ajax/libs/lightbox2/2.11.3/js/lightbox.min.js"></script>

    <script th:replace="~{common/header :: logout-script}"></script>

    <script th:inline="javascript">
        $(document).ready(function () {
            // 初始化高德地图
            const restaurant = /*[[${restaurant}]]*/ {};
            if (restaurant.latitude && restaurant.longitude) {
                // 确保经纬度是数值类型
                const lng = parseFloat(restaurant.longitude);
                const lat = parseFloat(restaurant.latitude);

                if (isNaN(lng) || isNaN(lat)) {
                    console.error("经纬度无效:", restaurant.name, lng, lat);
                    return;
                }

                // 创建地图实例
                const map = new AMap.Map('map', {
                    zoom: 15,
                    center: [lng, lat],
                    resizeEnable: true,
                    viewMode: '2D'
                });

                // 添加地图控件
                map.plugin(['AMap.ToolBar', 'AMap.Scale'], function () {
                    map.addControl(new AMap.ToolBar());
                    map.addControl(new AMap.Scale());
                });

                // 创建标记
                const marker = new AMap.Marker({
                    position: [lng, lat],
                    title: restaurant.name,
                    map: map
                });

                // 创建信息窗体
                const infoWindow = new AMap.InfoWindow({
                    content: `
                        <div style="padding: 8px 0;">
                            <h5 style="margin:0;">${restaurant.name}</h5>
                            <div style="display: flex; align-items: center; margin-top: 5px;">
                                <span style="color: #ffc107; margin-right: 5px;">
                                    ${restaurant.rating} <i class="fas fa-star"></i>
                                </span>
                                <span style="color: #28a745; margin-right: 5px;">
                                    ${'¥'.repeat(restaurant.priceLevel)}
                                </span>
                                <span>${restaurant.cuisineType}</span>
                            </div>
                        </div>
                    `,
                    offset: new AMap.Pixel(0, -30)
                });

                // 打开信息窗体
                infoWindow.open(map, marker.getPosition());
            }

            // 图片预览
            $('#imageFiles').change(function (e) {
                const files = e.target.files;
                $('#imagePreviewContainer').empty();

                for (let i = 0; i < files.length; i++) {
                    const file = files[i];
                    const reader = new FileReader();

                    reader.onload = function (e) {
                        const previewDiv = $('<div class="position-relative"></div>');
                        const img = $('<img class="image-preview">').attr('src', e.target.result);
                        const removeBtn = $('<div class="remove-image"><i class="fas fa-times"></i></div>');

                        removeBtn.click(function () {
                            previewDiv.remove();
                            // 注意：这里只是移除预览，实际提交时还需要处理文件列表
                        });

                        previewDiv.append(img).append(removeBtn);
                        $('#imagePreviewContainer').append(previewDiv);
                    }

                    reader.readAsDataURL(file);
                }
            });

            // 提交评论
            $('#reviewForm').submit(function (e) {
                e.preventDefault();

                // 获取表单数据
                const restaurantId = $('input[name="restaurantId"]').val();
                const rating = $('input[name="rating"]:checked').val();
                const content = $('#content').val();

                // 表单验证
                if (!rating || !content) {
                    alert('请填写评分和评论内容');
                    return;
                }

                // 获取图片文件
                const files = $('#imageFiles')[0].files;
                const imageUrls = [];
                let uploadedCount = 0;

                // 如果没有图片，直接提交评论
                if (files.length === 0) {
                    submitReview(imageUrls);
                    return;
                }

                // 上传图片
                for (let i = 0; i < files.length; i++) {
                    const formData = new FormData();
                    formData.append('file', files[i]);

                    $.ajax({
                        url: '/api/restaurants/upload-image',
                        type: 'POST',
                        data: formData,
                        processData: false,
                        contentType: false,
                        success: function (res) {
                            if (res.code === 200) {
                                imageUrls.push(res.data);
                                uploadedCount++;

                                // 所有图片上传完成后提交评论
                                if (uploadedCount === files.length) {
                                    submitReview(imageUrls);
                                }
                            } else {
                                alert('图片上传失败: ' + res.msg);
                            }
                        },
                        error: function (xhr) {
                            console.error('图片上传失败:', xhr);
                            alert('图片上传失败');
                            uploadedCount++;

                            // 即使有图片上传失败，也继续提交评论
                            if (uploadedCount === files.length) {
                                submitReview(imageUrls);
                            }
                        }
                    });
                }
            });

            // 提交评论函数
            function submitReview(imageUrls) {
                // 构建JSON数据
                const reviewData = {
                    restaurantId: $('input[name="restaurantId"]').val(),
                    rating: $('input[name="rating"]:checked').val(),
                    content: $('#content').val(),
                    imageUrls: imageUrls
                };

                // 发送请求
                $.ajax({
                    url: '/api/restaurants/reviews',
                    type: 'POST',
                    data: JSON.stringify(reviewData),
                    contentType: 'application/json',
                    success: function (res) {
                        if (res.code === 200) {
                            alert('评论发表成功！');
                            window.location.reload();
                        } else {
                            alert(res.msg || '评论发表失败，请重试');
                        }
                    },
                    error: function (xhr) {
                        console.error('评论提交失败:', xhr);
                        alert('评论发表失败，请重试');
                    }
                });
            }
        });
    </script>
</body>

</html>